import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/pages/home_page.dart';
import 'package:material_collection_app/utils/device_info.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/storage_util.dart';
import 'package:material_collection_app/utils/utils.dart';
import 'package:material_collection_app/widget/login/login_background.dart';
import 'package:material_collection_app/widget/login/login_item.dart';
import 'package:material_collection_app/widget/common/move_animation.dart';

import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'dart:convert';

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<LoginPage> {
  TextEditingController _accountController = new TextEditingController();
  TextEditingController _pwdController = new TextEditingController();

  void checkForm(context) async {
    var account = _accountController.text.trim();
    var password = _pwdController.text.trim();

    if (account == '') {
      Utils.showText(text: '请输入账号');
      return;
    }

    if (password == '') {
      Utils.showText(text: '请输入密码');
      return;
    }

    login(account, password);

    // checkUUID(account, password);
  }

  void checkUUID(account, password) async {
    var platformUid = await FlutterDeviceInfo.platformUid;

    DioUtils.request("login/checkImei",
        method: "POST", params: {'imei': platformUid}, onSuccess: (res) {
      if (res['code'] == 1) {
        login(account, password);
      } else if (res['code'] == 0) {
        Utils.showText(text: '移动设备管理不存在该设备');
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  void login(account, password) {
    //进行MD5加密
    var md5Content = new Utf8Encoder().convert(password);
    var md5digest = md5.convert(md5Content);
    var md5Str = hex.encode(md5digest.bytes);
    //进行base64加密
    var content = utf8.encode(password);
    var base64Digest = base64Encode(content);

    var pwd = base64Digest + '---' + md5Str;

    DioUtils.request("login/dologin",
        method: "POST",
        params: {'username': account, 'password': pwd}, onSuccess: (res) {
      if (res['code'] == 1) {
        String token = res['data']['token'];
        String uid = res['data']['uid'].toString();
        StorageUtil.setStringItem('token', token);
        StorageUtil.setStringItem('uid', uid);

        Navigator.of(context).pushAndRemoveUntil(
            MaterialPageRoute(builder: (context) => HomePage()),
            (route) => route == null);
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
    /*
    Navigator.of(context).pushAndRemoveUntil(
        MaterialPageRoute(builder: (context) => HomePage()),
        (route) => route == null);
    */
  }

  @override
  Widget build(BuildContext content) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Scaffold(
        backgroundColor: Colors.white,
        body: ConstrainedBox(
            constraints: BoxConstraints.expand(),
            child: Stack(alignment: Alignment.topCenter, children: <Widget>[
              LoginBackground(),
              Positioned(
                  top: 534.w,
                  child: ClipRRect(
                      borderRadius: BorderRadius.vertical(
                          top: Radius.elliptical(60.w, 60.w)),
                      child: GestureDetector(
                          behavior: HitTestBehavior.translucent,
                          onTap: () async {
                            FocusScope.of(context).requestFocus(FocusNode());
                          },
                          child: Container(
                              width: 750.w,
                              height: 800.w,
                              color: Colors.white,
                              padding: EdgeInsets.only(top: 156.w),
                              child: Column(children: <Widget>[
                                LoginItem(
                                  hintText: "用户名或邮箱",
                                  prefixIcon:
                                      Image.asset('assets/login_account.png'),
                                  controller: _accountController,
                                ),
                                LoginItem(
                                  obscureText: true,
                                  hintText: "请输入登录密码",
                                  prefixIcon:
                                      Image.asset('assets/login_pwd.png'),
                                  controller: _pwdController,
                                ),
                                Container(
                                  width: 395.w,
                                  margin:
                                      EdgeInsets.only(top: 5.w, bottom: 70.w),
                                  child: Text(
                                    '温馨提示：忘记密码请联系管理员，将重新分配登录密码',
                                    textAlign: TextAlign.center,
                                    style: TextStyle(
                                        color: Color(0xFF999999), fontSize: 13),
                                  ),
                                ),
                                BoxMoveAnimation(
                                    duraction: 300,
                                    child: SizedBox(
                                        width: 600.w,
                                        height: 120.w,
                                        child: ElevatedButton(
                                          onPressed: () {
                                            checkForm(context);
                                          },
                                          child: Text(
                                            '立即登录',
                                            style:
                                                TextStyle(color: Colors.white),
                                          ),
                                          style: ElevatedButton.styleFrom(
                                              backgroundColor:
                                                  Color(0xFF297CFF),
                                              shape: RoundedRectangleBorder(
                                                  borderRadius:
                                                      BorderRadius.all(
                                                          Radius.circular(
                                                              60.w)))),
                                        )))
                              ]))))),
              Container(
                width: 208.w,
                height: 208.w,
                alignment: Alignment.center,
                margin: EdgeInsets.only(top: 440.w),
                decoration: BoxDecoration(
                  border: new Border.all(color: Colors.white, width: 4),
                  borderRadius: BorderRadius.circular(200.w),
                  boxShadow: [
                    BoxShadow(
                        color: Color(0x99D4D4D4),
                        offset: Offset(0, 5),
                        blurRadius: 5.0,
                        spreadRadius: 0)
                  ],
                ),
                child: Image.asset(
                  'assets/avatar.png',
                  width: 200.w,
                  height: 200.w,
                ),
              )
            ])));
  }
}
